﻿using System;
using System.Data;
using System.Xml;

namespace ReadXMLFile
{
    public class xmlObj
    {
        public xmlObj()
        { 
        }

        public DataSet xmlStr2Ds(string xmlString)
        {
            DataSet dsBO = new DataSet();
            XmlDocument xml = new XmlDocument();
            // xmlString = "<ROOT><BOMS><BOM><BOS><BO><AdmInfo><Object>13</Object></AdmInfo><OINV><row><DocEntry>1</DocEntry><DocNum>1</DocNum><DocType>I</DocType><Handwrtten>N</Handwrtten><Printed>N</Printed><DocDate>20060122</DocDate><DocDueDate>20060222</DocDueDate><CardCode>C20000</CardCode></row></OINV><INV1><row><LineNum>0</LineNum><ItemCode>A00001</ItemCode><Dscription>IBM Infoprint 1312</Dscription><Quantity>5.000000</Quantity></row><row><LineNum>1</LineNum><ItemCode>A00002</ItemCode><Dscription>IBM Infoprint 1222</Dscription><Quantity>5.000000</Quantity></row></INV1></BO></BOS></BOM></BOMS></ROOT>";
            xml.LoadXml(xmlString);
            BuildDataSet(dsBO, xml.ChildNodes);
            return dsBO;
        }

        private void BuildDataSet(DataSet ds, XmlNodeList parentNode)
        {
             foreach (XmlNode nodeParent in parentNode)
             {
                if (nodeParent.Name.Equals("BO"))
                {
                    foreach (XmlNode node in nodeParent.ChildNodes)
                    {
                        if (node.Name.Equals("AdmInfo")) continue;
                        BuildTable(ds, node);
                    }
                    break;
                }
                else
                {
                    BuildDataSet(ds, nodeParent.ChildNodes);
                }
             }
        }

        private void BuildTable(DataSet ads, XmlNode nodeTable)
        {
            DataTable dt = new DataTable(nodeTable.Name); // nodeTable.Name: table name
            XmlNode firstNode = nodeTable.FirstChild;
            foreach (XmlNode col in firstNode.ChildNodes)
            {
                dt.Columns.Add(new DataColumn(col.Name, Type.GetType("System.String")));
            }

            foreach (XmlNode rowNode in nodeTable.ChildNodes)
            {
                DataRow dr = dt.NewRow();
                foreach (XmlNode colValue in rowNode.ChildNodes)
                {
                    dr[colValue.Name] = colValue.InnerText;
                }
                dt.Rows.Add(dr);
            }
            ads.Tables.Add(dt);
        }
    }
}
